import logging
import configparser
import urllib2
from weibo import APIClient
from weibo import APIError

class WeiboActions(object):
    def getAPI(self,sender):
        config=configparser.WeiboConfigParser()
        app_key = config.getAppKey()
        app_secret = config.getAppSecret()
        url = config.getUrl()

        query = config.getToken_TSecret(sender)
        if query is not None:
            logging.info("Authing...")
            api = APIClient(app_key, app_secret)
            api.set_access_token(query.access_token, query.expires_in)
            return  api
        else:
            return None

    def publish_sina_weibo(self,weibo_content,sender):
        api = self.getAPI(sender)
        status = None
        if api is not None:
            logging.info("publishing...")
            try:
                status = api.post.statuses__update(status=weibo_content)
            except APIError as apierr:
                print str(apierr)
            except urllib2.HTTPError as err:
                print str(err)   # 记录HTTP状态码
                print err.read() # 同时记录错误代码
            return status
        else:
            return None

    def private_letter_weibo(self,weibo_content,sender,id):
        api = self.getAPI(sender)
        if api is not None:
            logging.info("sending letter...")
            status = api.new_direct_message(id=id,text=weibo_content)
            return status
        else:
            return None